package com.creator.jobmatcherresume.tools;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author: Hank.GUO
 * @Date: 2025/3/25 22:10
 * @Email: guohaihang0512@163.com
 * @Description
 */
// 余弦相似度实现
public class CosineSimilarity implements SimilarityCalculator {
    @Override
    public double calculateSimilarity(Set<String> keywords1, Set<String> keywords2) {
        Set<String> allKeywords = new HashSet<>();
        allKeywords.addAll(keywords1);
        allKeywords.addAll(keywords2);

        double[] vectorA = createVector(keywords1, allKeywords);
        double[] vectorB = createVector(keywords2, allKeywords);

        return new CosineSimilarity().cosineSimilarity(vectorA, vectorB);
    }

    public double cosineSimilarity(double[] vectorA, double[] vectorB) {
        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;

        for (int i = 0; i < vectorA.length; i++) {
            dotProduct += vectorA[i] * vectorB[i];
            normA += Math.pow(vectorA[i], 2);
            normB += Math.pow(vectorB[i], 2);
        }

        if (normA == 0 || normB == 0) {
            return 0.0; // 处理零向量情况
        }
        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }

    private double[] createVector(Set<String> keywords, Set<String> allKeywords) {
        // 创建词向量（可以使用TF-IDF权重）
        return allKeywords.stream()
                .mapToDouble(word -> keywords.contains(word) ? 1.0 : 0.0)
                .toArray();
    }
}
